package com.bw.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple2;


import javax.ws.rs.ServerErrorException;

public class DwdShopUv {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        String topic = "dwd_traffic";
        String groupId ="dwd_traffic";

        FlinkKafkaConsumer<String> KafkaConsumer = MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId);
        DataStreamSource<String> pageLog = env.addSource(KafkaConsumer);

        /*统计周期内买家访问您店铺（观看店铺自播直播间、
          观看自制全屏页短视频3秒及以上、
          浏览店铺自制图文3秒及以上、浏览全屏微详情、访问宝贝详情页及店铺其他页面*/

        SingleOutputStreamOperator<String> pages = pageLog.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String value) throws Exception {
                JSONObject jsonObject = JSON.parseObject(value);

                if (jsonObject.getJSONObject("page") != null) {
                    String string = jsonObject.getJSONObject("page").getString("page_action");
                    if (string.equals("a") ||
                            string.equals("b") ||
                            string.equals("c") ||
                            string.equals("e") ||
                            string.equals("f")) {
                        return true;
                    }
                    return false;
                } else {
                    return false;
                }
            }
        });



//        结构转换
        SingleOutputStreamOperator<JSONObject> mappedStream = pages.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    System.out.println("脏数据：" + value);
                }
            }
        });


//        过滤last_page_id 不为null的数据
        SingleOutputStreamOperator<JSONObject> filterPageStream = mappedStream.filter(
                jsonObj -> jsonObj
                        .getJSONObject("page")
                        .getString("last_page_id") == null);

        //按照mid分组

        KeyedStream<JSONObject, String> keyedStream = filterPageStream.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));


//        通过flink编程状态过滤独立访客记录
        SingleOutputStreamOperator<JSONObject> filteredStream = keyedStream.filter(new RichFilterFunction<JSONObject>() {

            private ValueState<String> lastVisitDt;

            @Override
            public void open(Configuration paramenters) throws Exception {
                super.open(paramenters);
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("last_visit_dt", String.class);
                valueStateDescriptor.enableTimeToLive(
                        StateTtlConfig.newBuilder(Time.days(1L))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build()
                );
                this.lastVisitDt = getRuntimeContext().getState(valueStateDescriptor);
            }


            @Override
            public boolean filter(JSONObject value) throws Exception {
                String visitDt = DateFormatUtil.toDate(value.getLong("ts"));
                String lastDt = lastVisitDt.value();
                if (lastDt == null || !lastDt.equals(visitDt)) {
                    lastVisitDt.update(visitDt);
                    return true;
                }
                return false;
            }
        });



        // 统计独立访客数
        SingleOutputStreamOperator<Tuple2<String, Integer>> uvCountStream = filteredStream
                .map(new MapFunction<JSONObject, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(JSONObject jsonObj) throws Exception {
                        return Tuple2.of(DateFormatUtil.toDate(jsonObj.getLong("ts")), 1);
                    }
                })
                .keyBy(tuple -> tuple.f0)
                .window(TumblingProcessingTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .apply(new WindowFunction<Tuple2<String, Integer>, Tuple2<String, Integer>, String, TimeWindow>() {
                    @Override
                    public void apply(String date, TimeWindow window, Iterable<Tuple2<String, Integer>> input, Collector<Tuple2<String, Integer>> out) throws Exception {
                        int count = 0;
                        for (Tuple2<String, Integer> tuple : input) {
                            count += tuple.f1;
                        }
                        out.collect(Tuple2.of(date, count));
                    }
                });
        uvCountStream.print(">>>>>>>>>>>>>> UV Count: ");

//        将独立访客数据写入到对应主题中
        String targetTopic = "dwd_Shop_uv";
        filteredStream.print(">>>>>>>>>>>>>>");
        FlinkKafkaProducer<String> kafkaProducer = MyKafkaUtil.getFlinkKafkaProducer(targetTopic);
        filteredStream.map(a->a.toJSONString()).addSink(kafkaProducer);

        env.execute();
    }

}
